package com.sl.hx.shop.http;


import android.support.annotation.Nullable;

import com.sl.hx.shop.base.BaseFragmentView;
import com.sl.hx.shop.base.BaseView;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.FragmentEvent;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 对返回结果的预处理类
 * <p>
 * Created by hwg on 2017/12/20.
 */

public class RxHelper {

    /**
     * activity中使用
     *
     * @param mView
     * @param activityEvent
     * @param <T>
     * @return
     */
    public static <T> ObservableTransformer<HttpResult<T>, T> handleResult(final BaseView mView, final ActivityEvent activityEvent) {
        return new ObservableTransformer<HttpResult<T>, T>() {
            @Override
            public ObservableSource<T> apply(Observable<HttpResult<T>> upstream) {
                return upstream.flatMap(new Function<HttpResult<T>, ObservableSource<T>>() {
                    @Override
                    public ObservableSource<T> apply(HttpResult<T> result) throws Exception {

                        //根据实际情况判断
                        if (result.getCode() == 1) {
                            return createData(result.getData(), mView, activityEvent);
                        }
                         else {
                            return Observable.error(new ApiException(result.getMsg()));
                        }
                    }
                })
                        .subscribeOn(Schedulers.io())
                        .unsubscribeOn(Schedulers.io())
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

    /**
     * Fragment中使用
     *
     * @param mView
     * @param fragmentEvent
     * @param <T>
     * @return
     */
    public static <T> ObservableTransformer<HttpResult<T>, T> handleResult(final BaseFragmentView mView, final FragmentEvent fragmentEvent) {
        return new ObservableTransformer<HttpResult<T>, T>() {
            @Override
            public ObservableSource<T> apply(Observable<HttpResult<T>> upstream) {
                return upstream.flatMap(new Function<HttpResult<T>, ObservableSource<T>>() {
                    @Override
                    public ObservableSource<T> apply(HttpResult<T> result) throws Exception {

                        //根据实际情况判断
                        if (result.getCode() == 1) {
                                return createData(result.getData(), mView, fragmentEvent);

                        } else {
                                return Observable.error(new ApiException(result.getMsg()));
                        }
                    }
                })
                        .subscribeOn(Schedulers.io())
                        .unsubscribeOn(Schedulers.io())
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

    /**
     * 创建新的Observable并发送解析后的数据
     * Activity中使用
     *
     * @param data
     * @param mView
     * @param activityEvent
     * @param <T>
     * @return
     */
    private static <T> Observable<T> createData(@Nullable final T data, BaseView mView, ActivityEvent activityEvent) {
        return Observable.create(new ObservableOnSubscribe<T>() {
            @Override
            public void subscribe(ObservableEmitter<T> e) throws Exception {
                try {
                    if (data != null) {
                        e.onNext(data);
                        e.onComplete();
                    } else {
                        e.onComplete();
                    }
                } catch (Exception exception) {
                    e.onError(exception);
                }
            }
        }).compose(mView.<T>bindToLife(activityEvent));
    }

    /**
     * 创建新的Observable并发送解析后的数据
     * Fragment中使用
     *
     * @param data
     * @param mView
     * @param fragmentEvent
     * @param <T>
     * @return
     */
    private static <T> Observable<T> createData(final T data, BaseFragmentView mView, FragmentEvent fragmentEvent) {
        return Observable.create(new ObservableOnSubscribe<T>() {
            @Override
            public void subscribe(ObservableEmitter<T> e) throws Exception {
                try {
                    if (data != null){
                        e.onNext(data);
                        e.onComplete();
                    }else{
                        e.onComplete();
                    }
                } catch (Exception exception) {
                    e.onError(exception);
                }
            }
        }).compose(mView.<T>bindToLife(fragmentEvent));
    }

}
